package com.bora_bandeco;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.AsyncTask;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class CardapioFetcher extends AsyncTask<String, Void, String> {
	private static final String CARDAPIO_URL = "http://www.students.ic.unicamp.br/~ra104864/bora_bandeco/cardapio.php";
	public final static int TIMEOUT = 10;
	private TextView cardapioView;
	private ImageView loaderView;
	private Button tentarNovamente;
	private Activity cardapioActivity;
	
	public CardapioFetcher(Activity cardapioActivity) {
		super();
		
		this.cardapioActivity = cardapioActivity;
		
		this.cardapioView = (TextView)cardapioActivity.findViewById(R.id.cardapio);
		this.loaderView = (ImageView)cardapioActivity.findViewById(R.id.loader);
		this.tentarNovamente = (Button)cardapioActivity.findViewById(R.id.tentar_novamente);
	}
	
	@Override
	protected String doInBackground(String... urls) {
		String cardapio = this.getCardapio(CardapioFetcher.CARDAPIO_URL);
		return cardapio;
	}
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		 
		this.cardapioView.setVisibility(View.GONE);
		this.tentarNovamente.setVisibility(View.GONE);
		this.loaderView.setVisibility(View.VISIBLE);
	}
	
	@Override
	protected void onPostExecute(String result) {
		//Se o resultado da requisição é vazio, 
		//pode ser que não haja conexão, sendo assim exibir botão 
		//para tentar novamente buscar o cardápio 
		if (result == null) {
			this.cardapioView.setVisibility(View.GONE);
			this.tentarNovamente.setVisibility(View.VISIBLE);
			
			int duration = Toast.LENGTH_LONG;

			Toast toast = Toast.makeText(cardapioActivity, R.string.erro_fetch_cardapio, duration);
			toast.show();
		} else {
			this.cardapioView.setText(Html.fromHtml(result));
		    this.cardapioView.setVisibility(View.VISIBLE);
		    this.tentarNovamente.setVisibility(View.GONE);
		}
		this.loaderView.setVisibility(View.GONE);
	}
	
	private DefaultHttpClient createHttpClient() {
		final SchemeRegistry supportedSchemes = new SchemeRegistry();

		supportedSchemes.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
		supportedSchemes.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

		final HttpParams params = new BasicHttpParams();

		HttpConnectionParams.setConnectionTimeout(params, CardapioFetcher.TIMEOUT * 1000);
		HttpConnectionParams.setSoTimeout(params, CardapioFetcher.TIMEOUT * 1000);
		HttpConnectionParams.setSocketBufferSize(params, 8192);

		HttpClientParams.setRedirecting(params, false);

		final ClientConnectionManager com = new ThreadSafeClientConnManager(params, supportedSchemes);

		return new DefaultHttpClient(com, params);
	}
	
	private String getCardapio(String url) {
		HttpGet httpGet = new HttpGet(url);
		
		DefaultHttpClient httpClient = createHttpClient();

		HttpResponse httpResponse;
		try {
			httpResponse = httpClient.execute(httpGet);
			String response = EntityUtils.toString(httpResponse.getEntity());
			
			return response;
		} catch (ClientProtocolException e) {
			//
		} catch (IOException e) {
			//
		}
		return null;
	}
}
